<!--处理标签-->
<template>
  <div class="member-container">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchObj">
        <el-form-item label="用户名">
          <el-input v-model="searchObj.username" placeholder="请输入用户名" clearable />
        </el-form-item>

        <el-form-item label="真实姓名">
          <el-input v-model="searchObj.real_name" placeholder="请输入真实姓名" clearable />
        </el-form-item>

        <el-form-item label="电话">
          <el-input v-model="searchObj.phone" placeholder="请输入电话" clearable />
        </el-form-item>

        <el-form-item>
          <!-- 新增按钮 -->
          <el-button type="success" @click="handleAdd">
            <el-icon><Plus /></el-icon> 新增
          </el-button>
          <!-- 查询按钮 -->
          <el-button type="primary" @click="search">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card>
      <el-table v-loading="loading" :data="tableData" style="width: 100%">
<!--        <el-table-column prop="user_id" label="ID" width="80" />-->
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="real_name" label="真实姓名" width="120" />
        <el-table-column prop="phone" label="电话" width="130" />
        <el-table-column prop="address" label="地址" />
        <el-table-column prop="register_time" label="注册时间" width="180" />

        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          class="pagination"
          v-model:current-page="searchObj.current"
          v-model:page-size="searchObj.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          @current-change="loadData"
          @size-change="handleSizeChange"
      />
    </el-card>

    <!-- 编辑用户弹窗 -->
    <el-dialog v-model="dialogFormVisible" title="编辑用户" width="500px">
      <el-form-item :model="form" label-width="100px">
        <el-form-item label="用户名" :label-width="formLabelWidth" required>
          <el-input v-model="form.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth">
          <el-input v-model="form.password" type="password" autocomplete="off" placeholder="不修改请留空" />
        </el-form-item>
        <el-form-item label="真实姓名" :label-width="formLabelWidth">
          <el-input v-model="form.real_name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth" required>
          <el-input v-model="form.phone" autocomplete="off" />
        </el-form-item>
        <el-form-item label="地址" :label-width="formLabelWidth">
          <el-input v-model="form.address" autocomplete="off" />
        </el-form-item>
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确认修改</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增用户弹窗 -->
    <el-dialog v-model="addDialogVisible" title="新增用户" width="500px">
      <el-form :model="addForm" label-width="100px">
        <el-form-item label="用户名" :label-width="formLabelWidth" required>
          <el-input v-model="addForm.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" required>
          <el-input v-model="addForm.password" type="password" autocomplete="off" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="真实姓名" :label-width="formLabelWidth">
          <el-input v-model="addForm.real_name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth" required>
          <el-input v-model="addForm.phone" autocomplete="off" />
        </el-form-item>
        <el-form-item label="地址" :label-width="formLabelWidth">
          <el-input v-model="addForm.address" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddSubmit">确认新增</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<!--处理数据的-->
<script setup>
import { ref, onMounted } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import api from '@/api/member_api.js';
import { ElMessage, ElMessageBox } from 'element-plus';
import { cloneDeep } from 'lodash';

// 表格数据相关
const tableData = ref([]);//存储表格数据
const total = ref(0);//存储数据总数
const loading = ref(false);//控制加载状态

// 查询参数，也包含分页参数
const searchObj = ref({
  current: 1,
  limit: 10,
  username: '',
  real_name: '',
  phone: '',
  address: ''
});

// 编辑弹窗相关
const dialogFormVisible = ref(false); // 控制编辑对话框的显示/隐藏状态
const formLabelWidth = '120px'; // 设置表单标签的宽度
const form = ref({ // 响应式对象，存储编辑表单的数据
  user_id: '',      // 用户ID
  username: '',     // 用户名
  password: '',     // 密码字段
  real_name: '',    // 真实姓名
  phone: '',        // 电话
  address: ''       // 地址
});

// 新增弹窗相关
const addDialogVisible = ref(false); // 控制新增对话框的显示/隐藏状态
const addForm = ref({ // 响应式对象，存储新增表单的数据
  username: '',     // 用户名
  password: '',     // 密码字段
  real_name: '',    // 真实姓名
  phone: '',        // 电话
  address: ''       // 地址
});

// 加载表格数据
const loadData = async () => {
  loading.value = true;
  try {
    // 过滤空值参数
    const params = {};
    for (const [key, value] of Object.entries(searchObj.value)) {
      if (value !== '' && value !== undefined && value !== null) {
        params[key] = value;
      }
    }

    const res = await api.page(params);
    console.log(res)

    if (res) {
      tableData.value = res.data || [];
      total.value = res.count || 0;
    } else {
      ElMessage.error('获取数据失败');
      tableData.value = [];
    }
  } catch (error) {
    console.error('API请求错误:', error);
    ElMessage.error('加载数据失败');
    tableData.value = [];
  } finally {
    loading.value = false;
  }
};

// 搜索方法
const search = async () => {
  searchObj.value.current = 1; // 重置为第一页
  await loadData();
};

// 打开新增弹窗
const handleAdd = () => {
  // 重置表单
  addForm.value = {
    username: '',
    password: '',  // 重置密码
    real_name: '',
    phone: '',
    address: ''
  };
  addDialogVisible.value = true;
};

// 提交新增表单
const handleAddSubmit = async () => {
  try {
    // 表单验证
    if (!addForm.value.username) {
      ElMessage.warning('请输入用户名');
      return;
    }
    if (!addForm.value.password) {  // 验证密码
      ElMessage.warning('请输入密码');
      return;
    }
    if (!addForm.value.phone) {
      ElMessage.warning('请输入电话');
      return;
    }

    // 调用新增接口
    await api.add(addForm.value);
    ElMessage.success('新增成功');
    // 关闭弹窗并刷新数据
    addDialogVisible.value = false;
    loadData();
  } catch (error) {
    console.error('新增失败:', error);
    ElMessage.error('新增失败，请重试');
  }
};

// 编辑用户
const handleEdit = (row) => {
  dialogFormVisible.value = true;
  form.value = cloneDeep(row);
  // 清空密码（避免显示原密码）
  form.value.password = '';
};

// 提交编辑表单
const handleSubmit = async () => {
  try {
    // 表单验证
    if (!form.value.username) {
      ElMessage.warning('请输入用户名');
      return;
    }
    if (!form.value.phone) {
      ElMessage.warning('请输入电话');
      return;
    }

    // 调用编辑接口
    await api.edit(form.value);
    ElMessage.success('修改成功');
    dialogFormVisible.value = false;
    loadData();
  } catch (error) {
    console.error('修改失败:', error);
    ElMessage.error('修改失败，请重试');
  }
};

// 单行删除用户
const handleDelete = async (index, row) => {
  try {
    const confirmResult = await ElMessageBox.confirm(
        `确定要删除用户 "${row.username}" 吗?`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    );

    if (confirmResult === 'confirm') {
      await api.del(row.user_id);
      ElMessage.success('删除成功');
      loadData();
    }
  } catch (error) {
    // 修正取消操作的错误判断
    if (!(error instanceof Error && error.message === 'cancel')) {
      console.error('删除错误:', error);
      ElMessage.error('删除失败');
    }
  }
};

// 处理分页大小变化
const handleSizeChange = (val) => {
  searchObj.value.limit = val;
  searchObj.value.current = 1;
  loadData();
};

// 初始化加载
onMounted(() => {
  loadData();
});
</script>

<style scoped>
.member-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  justify-content: center;
}

/* 按钮间距 */
:deep(.el-button) {
  margin-right: 8px;
}
</style>
